<template>
  <!-- 主要内容区 -->
  <main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-100 p-6">
    <div class="bg-white rounded-lg shadow p-6">
      <h2 class="text-2xl font-semibold mb-6">通知公告管理</h2>
      <!-- 搜索和筛选区 -->
      <div class="mb-6 flex items-center">
        <el-input
          v-model="filters.content"
          placeholder="请输入标题"
          class="w-64 mr-4 mb-2"
        />
        <el-input
          v-model="filters.author"
          placeholder="请输入发布人"
          class="w-64 mr-4 mb-2"
        />
        <el-select
          v-model="filters.status"
          placeholder="状态"
          class="w-32 mr-4 mb-2"
        >
          <el-option label="全部" value="" />
          <el-option label="已发布" value="published" />
          <el-option label="草稿" value="draft" />
        </el-select>
        <el-button
          type="primary"
          @click="handleSearch"
          class="!rounded-button mb-2"
          >搜索</el-button
        >
        <el-button @click="handleReset" class="!rounded-button mb-2"
          >重置</el-button
        >
      </div>

      <!-- 操作按钮区 -->
      <div class="mb-4 flex">
        <el-button
          type="primary"
          @click="showAddDialog"
          class="!rounded-button mr-2"
        >
          <el-icon class="mr-1"><plus/></el-icon>新增
        </el-button>
        <el-button
          type="danger"
          @click="handleBatchDelete"
          class="!rounded-button mr-2"
        >
          <el-icon class="mr-1"><delete /></el-icon>删除
        </el-button>
      </div>

      <!-- 通知列表 -->
      <el-table
        :data="allNotice"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="序号" width="80" />
        <el-table-column prop="content" label="标题" min-width="200" />
        <el-table-column prop="createUser" label="发布人" width="120" />
        <el-table-column prop="createTime" label="发布时间" width="180" :formatter="formatDate"/>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'info'"
            >
              {{ scope.row.status === 0 ? "已发布" : "草稿" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleView(scope.row)"
              class="whitespace-nowrap"
              >查看</el-button
            >
            <el-button
              link
              type="primary"
              @click="showEditDialog(scope.row)"
              class="whitespace-nowrap"
              >编辑</el-button
            >
            <el-button
              link
              type="danger"
              @click="showSingleDeleteConfirm(scope.row)"
              class="whitespace-nowrap"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-4 flex justify-between items-center">
        <span class="text-sm text-gray-500"> 共 {{ total }} 条记录 </span>
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 新增弹窗 -->
      <el-dialog title="新增通知" v-model="addDialogVisible">
        <el-form :model="addForm">
          <el-form-item label="标题" label-width="100px">
            <el-input v-model="addForm.content"></el-input>
          </el-form-item>
          <el-form-item label="状态" label-width="100px">
            <el-select v-model="addForm.status" placeholder="状态">
              <el-option label="已发布" value="0" />
              <el-option label="草稿" value="1" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="createNotification">保存</el-button
            >
          </span>
        </template>
      </el-dialog>

      <!-- 查看弹窗 -->
      <el-dialog title="查看通知" v-model="viewDialogVisible">
        <el-form :model="viewForm">
          <el-form-item label="标题" label-width="100px">
            <el-input v-model="viewForm.title" disabled></el-input>
          </el-form-item>
          <el-form-item label="发布人" label-width="100px">
            <el-input v-model="viewForm.author" disabled></el-input>
          </el-form-item>
          <el-form-item label="发布时间" label-width="100px" >
            <el-input v-model="viewForm.publishTime" disabled ></el-input>
          </el-form-item>
          <el-form-item label="状态" label-width="100px" prop="status">
            <el-input v-model="viewForm.status" disabled>
            </el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="viewDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 编辑弹窗 -->
      <el-dialog title="编辑通知" v-model="editDialogVisible">
        <el-form :model="editForm">
          <el-form-item label="标题" label-width="100px">
            <el-input v-model="editForm.content"></el-input>
          </el-form-item>
          <el-form-item label="状态" label-width="100px">
            <el-select v-model="editForm.status" placeholder="状态">
              <el-option label="已发布" :value="0" />
              <el-option label="草稿" :value="1" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="updateNotification">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </main>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Bell,
  FullScreen,
  Setting,
  Plus,
  Delete,
  Upload,
  Download,
} from "@element-plus/icons-vue";
import {getAnnouncementList, addNotice, editNotice, delFrom} from "@/api/admin/notice";

// 日期格式化方法
const formatDate = (row, column, cellValue) => {
    if (!cellValue) return '';
    const d = new Date(cellValue);
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`; // 返回 yyyy-mm-dd 格式
};

const searchKeyword = ref("");
const filters = reactive({
  content: "",
  author: "",
  dateRange: [],
  status: "",
});

const notifications = ref([
  {
    id: 1,
    title: "关于2024年春节放假安排的通知",
    author: "贵州大学",
    publishTime: "2024-01-15 10:30:00",
    status: "published",
  },
  {
    id: 2,
    title: "2024年第一季度业绩报告会议通知",
    author: "贵州人文科技学院",
    publishTime: "2024-01-16 14:00:00",
    status: "published",
  },
  {
    id: 3,
    title: "新版ERP系统上线培训通知",
    author: "贵州大学",
    publishTime: "2024-01-17 09:00:00",
    status: "draft",
  },
  {
    id: 4,
    title: "年度员工满意度调查开始通知",
    author: "贵州大学",
    publishTime: "2024-01-18 11:30:00",
    status: "published",
  },
  {
    id: 5,
    title: "公司五周年庆典活动预告",
    author: "贵州大学",
    publishTime: "2024-01-19 16:00:00",
    status: "draft",
  },
]);
const total = ref(100);
const pageNum = ref(1);
const pageSize = ref(10);
const selectedRows = ref([]);
const addDialogVisible = ref(false);
const viewDialogVisible = ref(false);
const editDialogVisible = ref(false);

onMounted(() => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...filters
  }
  getNotice(params);
});

const form = ref({
  id: "",
  title: "",
  author: "",
  publishTime: "",
  status: "",
});
const addForm = reactive({
  title: "",
  author: "",
  publishTime: "",
  status: "",
});

const viewForm = reactive({
  title: "",
  author: "",
  publishTime: "",
  status: "",
});

const editForm = reactive({
  id: "",
  content: "",
  status: "",
});

//获取全部通知
//存储返回的所有数据
let allNotice = ref([]);
async function getNotice(data) {
  await getAnnouncementList(data).then(function (response) {
    allNotice.value = response.rows;
  });
}

//搜索按钮
const handleSearch = () => {
  ElMessage.success("搜索功能已触发");
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...filters
  }
  getNotice(params)
};

//重置按钮
const handleReset = () => {
  Object.assign(filters, {
    content: "",
    author: "",
    dateRange: [],
    status: "",
  });
};

const handleAdd = () => {
  ElMessage.success("新增通知功能已触发");
};

//新增弹窗
const showAddDialog = () => {
  addForm.content = "";
  addForm.status = "";
  addDialogVisible.value = true;
};

//保存新增数据
const createNotification = async () => {
  let res = await addNotice(addForm)
  if (!res || res.data.code === 200) {
    ElMessage.success("通知已成功添加");
    await getNotice({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    });
    addDialogVisible.value = false;
  } else {
    ElMessage.error("保存失败");
    addDialogVisible.value = false;
    throw new Error("新增内容保存失败");
  }
};

//批量删除
const handleSelectionChange = (val) => {
  selectedRows.value = val;
  console.log("选中的行：", val);
};
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择需要删除的通知");
    return;
  }
  await ElMessageBox.confirm("确定要删除选中的通知吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const ids = selectedRows.value.map((item) => item.id);
    const res = await delFrom(ids);
      ElMessage.success("删除成功");
      await getNotice({
            pageNum: pageNum.value,
            pageSize: pageSize.value,
            ...filters
          })
  }).catch(() => {
    ElMessage.info("取消删除!");
    return new Promise(() => {});
  });
};

//导入按钮
const handleImport = () => {
  ElMessage.info("导入功能已触发");
};

//导出按钮
const handleExport = () => {
  ElMessage.info("导出功能已触发");
};

//查看弹窗
const handleView = (row) => {
  viewForm.author = row.createUser;
  viewForm.publishTime = row.createTime;
  viewForm.status = row.status === 0 ? "已发布" : "草稿";
  viewForm.title = row.content;
  viewDialogVisible.value = true;
};

//编辑弹窗
const showEditDialog = (row) => {
  editForm.id = row.id
  editForm.status = row.status;
  editForm.content = row.content;
  editDialogVisible.value = true;
};

//编辑保存数据
const updateNotification = async () => {
  editNotice(editForm).then((res) => {
    if (!res || res.data.code === 200) {
      ElMessage.success("编辑成功");
      let params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        ...filters
      }
      getNotice(params);
      editDialogVisible.value = false;
    } else {
      ElMessage.error("编辑失败");
      editDialogVisible.value = false;
      throw new Error("编辑内容保存失败");
    }
    return res.data;
  });
};

//单行删除
const showSingleDeleteConfirm = async (row) => {
  ElMessageBox.confirm(`确定要删除通知：${row.content} 吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await delFrom([row.id]);
    let params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...filters
    }
    await getNotice(params);
  }).catch(() => {
    ElMessage.info("取消删除!");
    return new Promise(() => {});
  });

};

const handleSizeChange = (val) => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  };
  getNotice(params);
};

const handleCurrentChange = (val) => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  };
  getNotice(params);
};

const filteredNotifications = computed(() => {
  return notifications.value
    .filter(
      (notification) =>
        notification.title.includes(filters.title) &&
        notification.author.includes(filters.author) &&
        (filters.status === "" || notification.status === filters.status)
    )
    .slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value
    );
});
</script>

<style scoped>
/* 移除 input type="number" 的默认箭头 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

input[type="number"] {
  -moz-appearance: textfield;
}

/* 自定义滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style>
